package com.android.takeaway.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.math.BigDecimal;
import java.util.List;

import com.android.takeaway.R;
import com.android.takeaway.bean.Food;

/**
 * 物品详情适配器
 */
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.MyViewHolder> {
    private List<Food> foodBeanList;
    private Context context;

    public FoodAdapter(Context context) {
        this.context = context;
    }

    public void setData(List<Food> foodBeanList) {
        this.foodBeanList = foodBeanList;
        notifyDataSetChanged(); //刷新界面
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //加载订单列表
        View view = LayoutInflater.from(context).inflate(R.layout.food_item, parent, false);
        FoodAdapter.MyViewHolder holder = new FoodAdapter.MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Food foodBean = foodBeanList.get(position);
        // 获取图片的资源引用
        int resourceId = context.getResources().getIdentifier(foodBean.getFoodPic(), "mipmap", context.getPackageName());
        // 加载食物图片到holder
        Glide.with(context).load(resourceId).into(holder.iv_foodPic);

        holder.tv_foodName.setText(foodBean.getFoodName()); //显示食物名称
        holder.tv_count.setText("x" + foodBean.getCount());
        holder.tv_foodCost.setText("￥ " + foodBean.getPrice().multiply(BigDecimal.valueOf(foodBean.getCount())));
    }

    @Override
    public int getItemCount() {
        //判断list里面是否为空，如果是空则返回0否则返回本身长度
        return foodBeanList == null ? 0 : foodBeanList.size();
    }


    // 自定义的 ViewHolder 类，用于在 RecyclerView 中绑定和显示数据
    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv_foodName, tv_count, tv_foodCost;
        ImageView iv_foodPic;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            iv_foodPic = itemView.findViewById(R.id.iv_foodPic);
            tv_foodName = itemView.findViewById(R.id.tv_foodName);
            tv_count = itemView.findViewById(R.id.tv_count);
            tv_foodCost = itemView.findViewById(R.id.tv_foodCost);
        }
    }
}
